<template>
  <div class="zh-textbook-management">
    <nav-header>
      <div class="zh-h5-nav" v-if="crumbs === false">
        <div :class="activePanel === 'textbook-management' ? 'active' : ''" @click="changePanel('textbook-management')">
          教材管理</div>
        <div :class="activePanel === 'subject' ? 'active' : ''" @click="changePanel('subject')">科目管理</div>
      </div>
    </nav-header>

    <transition name="fade" mode="out-in" v-if="activePanel === 'textbook-management'">
      <div class="zh-table">
        <div class="zh-table-open clear">
          <div class="zh-open-left fl">
            <div class="open-width" style="width: 100px">
              <el-select v-model="listParam.org_id" filterable placeholder="请选择">
                <el-option v-for="item in orgLevel3" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="open-width" style="width: 100px">
              <el-select v-model="listParam.sub_id" filterable placeholder="请选择">
                <el-option v-for="item in orgSubject" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="open-width" style="width: 100px">
              <el-select v-model="listParam.ver_id" filterable placeholder="请选择">
                <el-option v-for="item in orgVersion" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="open-width">
              <el-input v-model="listParam.keyword" placeholder="请输入教材名称搜索" @keyup.enter.native="searchFunc"></el-input>
            </div>
            <el-button type="primary" @click="searchFunc">搜索</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
          </div>
          <div class="zh-open-right fr">
            <el-button type="primary" @click="saveMaterialBox">添加教材</el-button>
          </div>
        </div>
        <div class="zh-table-contents" v-loading="loading.status" :element-loading-text="loading.txt">
          <div class="zh-table-subject">
            <el-row :gutter="20">
              <template v-for="(item, index) in listData">
                <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="6" :key="index">
                  <el-card shadow="hover">
                    <div class="card-inner" @click="detailRoute(item.id, 'chapter')">
                      <div class="subject-content clear">
                        <div class="title-subject fl" :title="item.name">
                          <span>{{ item.name }}</span>
                        </div>
                        <div class="select-subject fr">
                          <i class="el-icon-close" @click.stop="deleteMaterial(item)" title="删除"></i>
                        </div>
                      </div>
                      <div class="chapter-subject">
                        {{ item.gvs_name }}
                      </div>
                      <div class="chapter-content">
                        章：<div>{{ item.cl_1_count }}</div>
                        节：<div>{{ item.cl_2_count }}</div>
                      </div>
                      <div class="chapter-content">
                        大知识点：<div>{{ item.big_know_count }}</div>
                        小知识点：<div>{{ item.small_know_count }}</div>
                      </div>
                      <div class="book-detail-btn">
                        <span @click.stop="detailRoute(item.id, 'chapter')">章节管理</span>
                        <span @click.stop="detailRoute(item.id, 'knowledge')">知识点管理</span>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </template>

            </el-row>
          </div>

          <div class="table-pagination" v-show="total_number > 20">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="listParam.page_index" :page-sizes="[20, 30, 40, 50, 100]" :page-size="listParam.page_size"
              layout="total, sizes, prev, pager, next, jumper" :total="total_number">
            </el-pagination>
            <div class="pagination-button">
              <el-button @click="getList" type="primary" icon="el-icon-refresh" circle title="刷新数据" size="mini">
              </el-button>
            </div>
          </div>
        </div>

        <!-- 添加/编辑教材 -->
        <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="添加教材"
          :visible.sync="teachingMaterial" class="teachingMaterial" width="400px">
          <el-form :model="addForm" ref="addForm" :rules="rules" status-icon label-position="left" label-width="80px">
            <el-form-item label="教材名称" prop="name">
              <el-input v-model.trim="addForm.name" placeholder="请输入教材名称" autocomplete="off" :maxlength="parseInt(20)"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="科目" prop="gvs_id">
              <el-select v-model="addForm.gvs_id" filterable @change="getGradeBoxData" placeholder="请选择"
                style="width:70%; margin-right: 5px; ">
                <el-option v-for="item in subjectData" :key="item.id" :label="item.name"
                  :value="item.subject_id + '-' + item.version_id">
                </el-option>
              </el-select>
              <el-button type="text" @click="subjectJump()">新增科目</el-button>
            </el-form-item>
            <el-form-item label="年级" prop="stu_id">
              <el-select v-model="addForm.stu_id" filterable placeholder="请选择">
                <el-option v-for="item in gradeBoxData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="teachingMaterial = false">取消</el-button>
            <el-button type="primary" @click="saveMaterial">确定</el-button>
          </div>
        </el-dialog>
      </div>
    </transition>
    <transition name="fade" mode="out-in" v-if="activePanel === 'subject'">
      <zh-subject-management />
    </transition>

  </div>
</template>
<script>
export default {
  data() {
    return {
      app_code: sessionStorage.getItem('CheckSchoolAppCode'),
      loading: {
        status: false,
        txt: '获取数据...',
      },
      activePanel: 'textbook-management',
      listData: [],//列表数据
      listParam: {//列表数据参数
        org_id: 0,
        sub_id: 0,
        ver_id: 0,
        keyword: '',
        page_index: 1,
        page_size: 20,
        app_code: '',
      },
      subjectData: [],//弹框科目下拉
      gradeBoxData: [],//弹框年级下拉
      orgLevelParam: { //获取年级参数
        level: 3,
        direction: 'balance',
      },
      orgLevel3: [],//年级数据
      orgSubject: [],//科目数据
      orgVersion: [],//版本数据
      subjectParam: { //获取科目参数
        type: 2,
        org_id: 1,
        status: 1,
      },
      versionParam: { //获取版本参数
        type: 2,
        org_id: 0,
        sub_id: 0,
        status: 1
      },
      total_number: 0,//数据总素

      teachingMaterial: false,
      addForm: {
        id: '',
        name: '',
        gvs_id: '',
        sub_id: '',
        ver_id: '',
        stu_id: '',
      },
      rules: {
        name: [
          { validator: this.checkChange, message: '请输入教材名称', trigger: 'blur', required: true }
        ],
        gvs_id: [
          { validator: this.checkChange, message: '请选择科目', trigger: 'change', required: true }
        ],
        stu_id: [
          { validator: this.checkChange, message: '请选择年级', trigger: 'change', required: true }
        ],
      },
      crumbs: false,
    }
  },
  created() {
    this.toggleView();
    this.initFunc();
  },
  watch: {
    $route() {
      this.toggleView()
    },
    'listParam.org_id': {
      handler(newVal, oldVal) {
        this.listParam.sub_id = 0;
        this.listParam.ver_id = 0;

        this.subjectParam.org_id = newVal;
        this.getSubject();

        this.versionParam.org_id = newVal;
        this.getVersion();
      }
    },
    'listParam.sub_id': {
      handler(newVal, oldVal) {
        this.listParam.ver_id = 0;

        this.versionParam.sub_id = newVal;
        this.getVersion();
      }
    },
    teachingMaterial() {
      if (this.teachingMaterial === false)
        this.$refs.addForm.resetFields()
    }
  },
  methods: {
    searchFunc() {
      this.listParam.page_index = 1;
      this.getList();
    },
    reset() {
      this.orgLevelParam = { //获取年级参数
        level: 3,
        direction: 'balance',
      }
      this.subjectParam = { //获取科目参数
        type: 2,
        org_id: 1,
        status: 1,
      }
      this.versionParam = { //获取版本参数
        type: 2,
        org_id: 0,
        sub_id: 0,
        status: 1
      }
      this.listParam = {
        org_id: 0,
        sub_id: 0,
        ver_id: 0,
        keyword: '',
        page_index: 1,
        page_size: 20,
      }
      this.getList();
    },
    initFunc() {
      this.getOrgLevel3();
      this.getSubject();
      this.getVersion();
      this.getList();
      this.getSubjectBoxData();

      if (this.$route.query.name === 'subject') {
        this.activePanel = 'subject';
      }
    },
    changePanel(panel) {
      this.activePanel = panel;
      if (this.activePanel == 'textbook-management') {
        this.$router.push("/resources/resource/textbook-management")
        // this.initFunc();
        this.getSubjectBoxData();
      }
    },
    subjectJump() {
      this.teachingMaterial = false;
      this.activePanel = 'subject';
    },
    checkChange(rule, value, callback) {
      if (!isEmpty(value)) {
        return callback(new Error('内容不能为空'));
      } else {
        callback()
      }
    },
    saveMaterialBox() {
      this.teachingMaterial = true;
      this.resetAddform();
      this.getList();
    },
    //保存教材
    saveMaterial() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.addForm.sub_id = this.addForm.gvs_id.split("-")[0];
          this.addForm.ver_id = this.addForm.gvs_id.split("-")[1];
          let success = (data => {
            this.teachingMaterial = false;
            this.$message.success(data.msg);
            this.getList();
          })
          if (this.$store.state.checkLevel) {
            this.$ajax.post('api/newlevel/platform_material', this.addForm, { func: { success: success } })
          } else {
            this.$ajax.post('api/cate/material', this.addForm, { func: { success: success } })
          }
        } else {
          return false
        }
      });
    },
    //获取添加教材弹框版本下拉数据
    getSubjectBoxData() {
      let success = (data => {
        this.subjectData = data.data;
      })
      //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
      if (this.$store.state.checkLevel) {
        this.$ajax.get('api/newlevel/platform_subject_data', { params: {}, func: { success: success } })
      } else {
        this.$ajax.get('api/cate/subject_data', { params: {}, func: { success: success } })
      }
    },
    //获取添加教材弹框年级下拉数据
    getGradeBoxData(params) {
      this.addForm.stu_id = '';
      var subject_id = params.split('-')[0];
      var version_id = params.split('-')[1];
      let success = (data => {
        this.gradeBoxData = data.data;
      })
      this.$ajax.get('api/org/get_grade_by_subject', { params: { subject_id: subject_id, version_id: version_id }, func: { success } })
    },
    //删除教材
    deleteMaterial(obj) {
      let yes = (data => {
        let success = (data => {
          this.$message.success(data.msg);
          if (this.listData.length === 1 && this.listParam.page_index > 1) {
            this.listParam.page_index--;
          }
          this.getList();
        })
        if (this.$store.state.checkLevel) {
          this.$ajax.delete('api/newlevel/platform_material', { params: { id: obj.id }, func: { success: success } })
        } else {
          this.$ajax.delete('api/cate/material', { params: { id: obj.id }, func: { success: success } })
        }
      })
      let cancel = (data => { })
      this.e_confirm({ yes: yes, cancel: cancel, txt: '确定删除 ' + obj.name + ' 吗？' });
    },
    //获取数据
    getList() {
      if (this.$store.state.checkLevel) {
        this.listParam.app_code = sessionStorage.getItem('CheckSchoolAppCode')
      }
      this.loading.status = true;
      let success = (data => {
        console.log(JSON.parse(JSON.stringify(data.data.data)), 1999)
        this.loading.status = false;
        this.listData = data.data.data.reverse();
        this.total_number = data.data.data_sum;
      })
      let fail = (data => {
        this.loading.status = false;
        this.$message.error(data.msg)
      })
      //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
      if (this.$store.state.checkLevel) {
        this.$ajax.get('api/newlevel/platform_material', { params: this.listParam, func: { success: success, fail: fail } })
      } else {
        this.$ajax.get('api/cate/material', { params: this.listParam, func: { success: success, fail: fail } })
      }

    },

    //获取年级
    // getOrgLevel3(){
    // 	let success = ( data=>{
    // 		this.orgLevel3 = data.data;
    // 		this.orgLevel3.unshift({id:0,name:'全部年级'})
    // 	})
    // 	this.$ajax.get('api/org/org',{params: this.orgLevelParam,func:{success:success}})
    // },
    getOrgLevel3() {
      if (this.$store.state.checkLevel) {
        this.orgLevelParam.app_code = this.app_code
      }
      let success = (data => {
        console.log(JSON.parse(JSON.stringify(data)), 300)
        this.orgLevel3 = data.data;
        this.orgLevel3.unshift({ id: 0, name: '全部年级' })
      })
      if (this.$store.state.checkLevel) {
        this.$ajax.get('api/network/get_platform_org', { params: this.orgLevelParam, func: { success: success } })
      } else {
        this.$ajax.get('api/org/org', { params: this.orgLevelParam, func: { success: success } })
      }
    },

    //获取科目
    getSubject() {
      if (this.$store.state.checkLevel) {
        this.subjectParam.app_code = this.app_code
      }
      let success = (data => {
        this.orgSubject = data.data;
        this.orgSubject.unshift({ id: 0, name: '全部科目' });
      })
      //todo
      let fail = (data => {

      })
      if (this.$store.state.checkLevel) {
        this.$ajax.get('api/newlevel/platform_subject', { params: this.subjectParam, func: { success: success } })
      } else {
        this.$ajax.get('api/cate/subject', { params: this.subjectParam, func: { success: success, fail: fail } })
      }
    },
    //获取版本
    getVersion() {
      let success = (data => {
        this.orgVersion = data.data;
        this.orgVersion.unshift({ id: 0, name: '全部版本' });
      })
      this.$ajax.get('api/cate/version', { params: this.versionParam, func: { success: success } })
    },
    //记录导航状态
    toggleView() {
      this.view = this.$route.name
    },
    /**
     * 跳到教材详情页
     * @param {Number} 教材 id
     * @param {String} 具体模块
     */
    detailRoute(id, name) {
      this.$store.commit('SET_ACTIVEPANEL', name);
      this.$router.push('/resources/resource/material-detail/' + id)
    },
    // subject(){
    // 	this.$router.push("/resources/resource/textbook-management/subject")
    // 	this.teachingMaterial = false
    // },
    // textbook(){
    // 	this.$router.push("/resources/resource/textbook-management")
    // },
    handleSizeChange(val) {
      this.listParam.page_index = 1;
      this.listParam.page_size = val;
      this.getList()
    },
    handleCurrentChange(val) {
      this.listParam.page_index = val;
      this.getList();
    },
    resetAddform() {
      this.addForm = {
        name: '',
        gvs_id: '',
        sub_id: '',
        ver_id: '',
        stu_id: '',
        app_code: ''
      }
    }
  },
}
</script>
<style lang="scss">
.zh-textbook-management,
.zh-subject-management {
  .book-detail-btn {
    display: flex;
    justify-content: space-between;
    padding: 16px 0 0;

    span {
      padding: 6px 16px;
      color: #fff;
      background: #409EFF;
      border-radius: 6px;
      cursor: pointer;
    }
  }

  .zh-table-contents {
    .zh-table-subject {
      padding-top: 30px;
      border-top: 1px solid #e6e6e6;

      >div {
        display: flex;
        flex-wrap: wrap;
      }

      .el-col {
        margin-bottom: 20px;

        .el-card {
          border: 1px solid #e6e6e6;
          cursor: pointer;

          &:hover {
            .title-subject {
              color: #409EFF;
            }
          }

          .el-card__body {
            padding: 0;
          }

          .card-inner {
            padding: 20px;
          }
        }

        .subject-content {
          width: 100%;

          .title-subject {
            width: 90%;
            font-size: 16px;
            font-weight: 600;


          }

          .select-subject {
            i {
              font-size: 20px;
              color: #999;

              &:hover {
                color: red;
                cursor: pointer;
              }
            }
          }
        }

        .subject-content,
        .title-subject,
        .chapter-subject {
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }

        .chapter-content {
          margin-top: 20px;

          div {
            display: inline-block;
            margin: 0 15px 0 5px;
            color: #409EFF;
          }
        }

        .chapter-subject {
          width: 100%;
          margin-top: 10px;
          color: #666;
        }
      }
    }
  }
}
</style>
